/**
 * @description 防御塔相关行为逻辑
 */
export const tower = (roomKey) => {
    /**
     * @type {Room}
     */
    const room = Game.rooms[roomKey]
    if (Memory.Rooms[roomKey].towers.length > 0 && room.controller.level >= 3) {
        /**
         * @type {StructureTower[]}
         */
        const towers = Memory.Rooms[roomKey].towers.map((id) => Game.getObjectById(id))
        if (towers.length > 0) {
            for (const tower of towers) {
                if (hasCreepInvasion(room)) {
                    towerAttack(tower)
                } else {
                    towerRepair(tower)
                }
            }
        }
    }
    // const towers = room.find(FIND_MY_STRUCTURES, {
    //     filter: {structureType: STRUCTURE_TOWER}
    // });

}

/**
 * @description 修复建筑物
 * @param {StructureTower} tower
 */
const towerRepair = (tower) => {
    // 获取距离当前防御塔最近的受损建筑
    const target = tower.room.find(FIND_STRUCTURES, {
        filter: (structure) => {
            return structure.hits <= structure.hitsMax / 2 && structure.structureType !== STRUCTURE_WALL && structure.structureType !== STRUCTURE_RAMPART;
        }
    });
    //获取刚刚修的wall和pampart
    const wall = tower.room.find(FIND_STRUCTURES, {
        filter: (structure) => {
            return structure.hits <= 300 && (structure.structureType === STRUCTURE_WALL || structure.structureType === STRUCTURE_RAMPART);
        }
    });
    // 如果找到了受损的建筑，则修复它
    if (target.length > 0) {
        tower.repair(target[0]);
    }
    if (wall) {
        tower.repair(wall[0])
    }
}
/**
 * @description 攻击入侵的creep
 * @param {StructureTower} tower
 */
const towerAttack = (tower) => {
    // 获取距离当前防御塔最近的敌对单位
    const target = tower.room.find(FIND_HOSTILE_CREEPS);
    // 如果找到了敌对单位，则攻击它
    if (target.length > 0) {
        tower.attack(target[0]);
    }

}

/**
 * 检查当前房间是否有入侵者
 * @param {Room} room
 * @returns {boolean}
 */
const hasCreepInvasion = (room) => {
    // 查找当前房间内的敌对单位
    const hostiles = room.find(FIND_HOSTILE_CREEPS);
    // 如果找到了敌对单位，则返回 true
    return hostiles.length > 0;
}
